package org.xbzheng.restful_study.interceptor;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.xbzheng.restful_study.util.ScrumConstant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This interceptor validates if there is a valid session when secure resources are being accessed, if not
 * redirects you back to timeout page with header set to 401. Check spring config for the intercepted path and
 * excluded path
 *
 */
public class SessionValidityInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final Object handler) throws Exception {

        if (request.getSession().getAttribute(ScrumConstant.USER) == null) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.sendRedirect(request.getContextPath());

            return false;
        }

        return true;
    }
}
